package com.terren.excavator.service.impl;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.jsoup.nodes.Document;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson.JSON;
import com.terren.excavator.config.ConfigInfo;
import com.terren.excavator.content.ExcavateContent;
import com.terren.excavator.entity.FolderHtml;
import com.terren.excavator.service.PublishService;
import com.terren.excavator.util.CommonUtil;
import com.terren.excavator.util.HtmlUtil;

@Service("publishService")
public class PublishServiceImpl implements PublishService {
	static Logger logger = CommonUtil.getLogger(PublishServiceImpl.class);
	
	/**
	 * 获得发稿日期
	 */
	public String getPublishDay(String publishUrl,String publishDayRule){
		String publishDay = null;
		try {
			ExcavateContent ec = new ExcavateContent(publishUrl);
			
			Long dayLong = ec.getPublishDay(publishDayRule);
			
			if(dayLong == null){
				publishDay = null;
			}else{
				publishDay = dayLong + "";
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return publishDay;
	}
	
	/**
	 * 获得转载网站名称
	 */
	public String getPublishName(String publishUrl,String publishNameRule){
		String publishName = null;
		try {
			ExcavateContent ec = new ExcavateContent(publishUrl);
			
			publishName = ec.getFirstPublish(publishNameRule);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return publishName;
	}
	
	/**
	 * 正则匹配
	 * @param firstPublish
	 * @param regex
	 * @return
	 */
	public String getRegexMatch(String firstPublish,String regex){
		if(firstPublish != null && regex != null){
			Pattern pattern = Pattern.compile(regex);
			//create a Matcher and use the Matcher.group() method
			Matcher matcher = pattern.matcher(firstPublish);
			// extract the group
			if(matcher.find()){
				firstPublish = matcher.group();
			}else{
				firstPublish = "正则匹配失败";
			}
		}
		return firstPublish;
	}
	
	/**
	 * 获得所有已下载的页面
	 * @return
	 */
	public String getDownloadHtmlJson(int start,int limit){
		String mainPath = CommonUtil.getWebMainPath();
		
		File downloadFolder = new File(mainPath + ConfigInfo.downloadHtmlPath);
		
		String[] fileArray = downloadFolder.list();
		
		List<FolderHtml> fileList = new ArrayList<FolderHtml>();
		
		int total = 0;
		if(fileArray != null){
			total = fileArray.length;
		}
		for(int i = start; i < limit; i++){
			if(i < total){
				String name = fileArray[i];
				
				FolderHtml folder = new FolderHtml(name);
				
				fileList.add(folder);
			}else{
				break;
			}
		}
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		jsonMap.put("total", total);
		jsonMap.put("rows", fileList);
		
		String jsonResult = JSON.toJSONString(jsonMap);
		return jsonResult;
	}
	
	/**
	 * 删除下载页面
	 * @param folderNameList
	 */
	public String deleteDownloadHtml(List<FolderHtml> folderNameList){
		String mainPath = CommonUtil.getWebMainPath() + ConfigInfo.downloadHtmlPath + "/";
		
		for(FolderHtml html : folderNameList){
			String folderName = html.getFolderName();
			String folderPath = mainPath + folderName;
			System.out.println("delete : " + folderPath);
			File folder = new File(folderPath);
			CommonUtil.deleteFolder(folder);
		}
		
		String resultJson = CommonUtil.returnAjaxJson(true, "删除成功！");
		return resultJson;
	}
	
	/**
	 * 下载新的页面
	 * @param downloadUrl
	 * @param htmlName
	 * @param encoding
	 * @return
	 */
	public String downloadNewHtml(String downloadUrl,String htmlName,String encoding){
		
		String pathFlag = File.separator;
		
		String htmlFolder = CommonUtil.getWebMainPath() + ConfigInfo.downloadHtmlPath + pathFlag + htmlName + pathFlag;
		
		CommonUtil.createFilePath(htmlFolder);
		
		System.out.println(htmlFolder);
		
		String fileName = "index.html";// 文件名称
		String namepostfix = "chinadaily";
		
		HtmlUtil htmlUtil = new HtmlUtil();
		
		Document doc = htmlUtil.copyURLToHtmlDoc(downloadUrl, 60000);// 根据Url抓取页面放入document对象
		if (doc != null) {
			File file = new File(htmlFolder);
			if (file.exists()) {
				try {
					FileUtils.cleanDirectory(file);
				} catch (IOException e) {
					logger.info("清空文件夹 :" + htmlFolder + " 错误");
				}
			}
			htmlUtil.makeHtmlLinkFile(doc, htmlFolder, 60000,encoding,namepostfix);// 根据u网页中css、js、img链接地址及文件名生成本地文件
			htmlUtil.renameHref(doc,namepostfix);// 把页面中link标签中的href属性改为本地的相对路径,正确加载css样式
			htmlUtil.removeHref(doc);// 去掉A链接
			
			String jsName = "UTF-8";
			
			if(!"UTF-8".equalsIgnoreCase(encoding)){
				jsName = "GBK";
			}
			String content = "<script type='text/javascript' src='../../js_lib/common/render-" + jsName + ".js' charset='" + jsName + "'></script>";
			
			doc = htmlUtil.appendLink(doc, "head", content);//在head标签中加载js
			htmlUtil.makeHtmlByDoc("",htmlFolder, fileName, doc, encoding);//生成html文件
		}
		
		String result = CommonUtil.returnAjaxJson(true, "下载成功！");
		
		return result;
	}
	
}
